package com.jumi.microservice.controller.api;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jm.member.common.api.volidator.Validator;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.jwt.constant.JwtAdminInfo;
import com.jm.member.common.redis.service.RedisService;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.config.RedisInit;
import com.jumi.microservice.dto.reponse.api.AreaResponse;
import com.jumi.microservice.dto.request.AddressUpdateRequest;
import com.jumi.microservice.entity.JmAddress;
import com.jumi.microservice.service.IJmAddressService;
import com.jumi.microservice.service.IJmAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 要挑客户管理团队
 * @since 2020-09-07
 */
@RestController
@RequestMapping("/api/jm-area")
@Api(tags = "C-地址管理")
public class JmAreaController {

    @Autowired
    IJmAreaService areaService;

    @Autowired
    IJmAddressService addressService;

    @PostMapping("/getArea")
    @ApiOperation(value = "查询地区信息")
    public ResponseResult getArea(@ApiParam(value = "父id",required = true) @RequestParam Integer parentId){
        if(ObjectUtil.isEmpty(parentId)){
            return ResponseResult.error("parentId不能为空!");
        }
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("area_parent_id",parentId);
        //wrapper.eq("area_deep",deep);
        List list = areaService.list(wrapper);
        return ResponseResult.success(list);
    }

    @Autowired
    RedisService redisService;

    @GetMapping("/getAreaList")
    @ApiOperation(value = "获取地址信息列表",tags = "获取地址信息列表",response = AreaResponse.class)
    public ResponseResult getAreaList(){
        List<AreaResponse> areaResponses = redisService.getCacheObject(RedisInit.REDIS_AREA_CACHE);
        return ResponseResult.success(areaResponses);
    }


    @PostMapping("/saveArea")
    @ApiOperation(value = "添加地址信息")
    public ResponseResult saveArea(@Validated AddressUpdateRequest request){
        Integer apiUserId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);

        checkDefaultAddress(apiUserId,request);
        JmAddress address=new JmAddress();
        BeanUtils.copyProperties(request,address);
        address.setUid(apiUserId);
        addressService.save(address);
        return ResponseResult.success(address);
    }

    @PostMapping("/updateArea")
    @ApiOperation(value = "修改地址信息")
    public ResponseResult updateArea(@Validated(Validator.UpdateValidator.class) AddressUpdateRequest request){
        Integer apiUserId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        Integer addressId = request.getAddressId();
        JmAddress byId = addressService.getById(addressId);
        if(ObjectUtil.isEmpty(byId)){
            return ResponseResult.error("未查询到相关记录");
        }
        checkDefaultAddress(apiUserId,request);
        BeanUtils.copyProperties(request,byId);
        byId.setUid(apiUserId);
        addressService.updateById(byId);
        return ResponseResult.success(byId);
    }

    public void checkDefaultAddress(Integer apiUserId,AddressUpdateRequest request){
        //判断用户是否存在默认地址
        //不存在时,request 强制为默认地址,  存在时,判断更新的记录是否为默认,如果为默认 需要把之前的默认地址更新
        JmAddress defaultAddress = addressService.getDefaultAddress(apiUserId);
        Integer isDefault = request.getIsDefault();

//        if(ObjectUtil.isEmpty(defaultAddress)){
//            request.setIsDefault(1);
//        }
        if(isDefault==1&&ObjectUtil.isNotEmpty(defaultAddress)){
            defaultAddress.setIsDefault(0);
            addressService.updateById(defaultAddress);
        }
    }

    @GetMapping("/getListByUser")
    @ApiOperation("获取当前用户的所有地址信息")
    public ResponseResult getListByUser(){
        Integer intHeader = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("uid",intHeader);
//        wrapper.orderByDesc("is_default");
        wrapper.orderByDesc("address_id");
        List list = addressService.list(wrapper);
        return ResponseResult.success(list);
    }

    @PostMapping("/getAddressById")
    @ApiOperation("获取单条地址信息")
    public ResponseResult getAddressById(Integer addressId){
        JmAddress byId = addressService.getById(addressId);
        return ResponseResult.success(byId);
    }

    @DeleteMapping("/deleteById")
    @ApiOperation("删除地址信息")
    @Transactional
    public ResponseResult deleteById(Integer addressId){
        Integer intHeader = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmAddress byId = addressService.getById(addressId);
        if(ObjectUtil.isEmpty(byId)) { return ResponseResult.error("未查询到相关记录");}
        if(!byId.getUid().equals(intHeader)){ return ResponseResult.error("用户信息不匹配!");}
        // 如果被删除的地址是默认地址,则自动将该用户最新的一个地址作为默认地址递进
//        if(byId.getIsDefault()==1){
//            JmAddress maxObj=addressService.findMaxNotDefaultObj(intHeader);
//            if(ObjectUtil.isNotEmpty(maxObj)){
//                maxObj.setIsDefault(1);
//                addressService.updateById(maxObj);
//            }
//
//        }
        addressService.removeById(byId.getAddressId());
        return ResponseResult.success();
    }

    @GetMapping("/getDefaultAddress")
    @ApiOperation(value = "获得用户的默认收货地址")
    public ResponseResult getDefaultAddress() {
        Integer intHeader = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid",intHeader);
        wrapper.eq("is_default",1);
        JmAddress address = addressService.getOne(wrapper);
        if(ObjectUtil.isNotEmpty(address)){
            return ResponseResult.success(address);
        }
        return ResponseResult.error("请添加地址信息");
    }

}
